<template>
  <canvas></canvas>
</template>

<script>
export default {
  name: "FlowingText",
  mounted() {
    this.init();
  },
  methods: {
    init() {
      var canvas = document.querySelector("canvas");
      var ctx = canvas.getContext("2d");

      // 获取父元素的宽高
      var width = document.getElementById("page-container").clientWidth;
      var height = document.getElementById("page-container").clientHeight;

      canvas.style.width = width + "px";
      canvas.style.height = height + "px";

      // 处理图像的清晰度
      var scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas.
      canvas.width = Math.floor(width * scale);
      canvas.height = Math.floor(height * scale);
      // 设置背景颜色为白色
      ctx.fillStyle = "#000";
      // 使用fillRect填充整个Canvas
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      const fontSize = 16 * scale;

      // 随机生成一个字符
      function randomString() {
        return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
      }

      // 范围内的随机整数
      function randomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }

      // 随机颜色
      function randomColor() {
        return `rgb(${randomInt(0, 255)},${randomInt(0, 255)},${randomInt(
          0,
          255
        )})`;
      }

      ctx.font = `${fontSize}px sans-serif`;
      const columns = Math.floor(canvas.width / fontSize);
      let rowIndex = new Array(columns).fill(0);

      function draw() {
        ctx.fillStyle = "rgba(0,0,0,0.05)";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.textBaseline = "top";
        for (let i = 0; i < columns; i++) {
          const text = randomString();
          ctx.fillStyle = randomColor();
          ctx.fillText(text, i * fontSize, rowIndex[i] * fontSize);
          if (rowIndex[i] * fontSize > canvas.height && Math.random() > 0.9) {
            rowIndex[i] = 0;
          }
          rowIndex[i]++;
        }
      }

      setInterval(() => {
        draw();
      }, 100);
    },
  },
};
</script>

<style>
</style>